package com.bw.ivideoproject.wight;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.SizeUtils;

public class FlowLayout extends ViewGroup {

    private int lastX = 0;
    private int lastY = 0;
    private int currentWidth = 0;
    private int currentHeight = 0;
    private boolean layouted = false;
    private int space = SizeUtils.dp2px(5.0F);

    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        currentHeight = getMeasuredHeight();
        currentWidth = getMeasuredWidth();
    }

    @Override
    protected void onLayout(boolean isChanged, int l, int t, int r, int b) {
        if(layouted){
            return;
        }

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View subView = getChildAt(i);
            if(lastX+subView.getMeasuredWidth()+(space*2) > currentWidth){
                lastY+= subView.getMeasuredHeight();
                lastX=0;
            }
            subView.layout(lastX+space,lastY+space,lastX+space+subView.getMeasuredWidth(),lastY+space+subView.getMeasuredHeight());
            lastX += subView.getMeasuredWidth()+space;;
        }
        layouted = true;
    }
}
